package com.jibei.mendo.utils;

import android.graphics.Color;
import android.os.Handler;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.jibei.mendo.MendoApplication;
import com.jibei.mendo.R;
import com.jibei.mendo.event.Event;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static com.jibei.mendo.utils.Constant.SERVER_IP;
import static com.jibei.mendo.utils.Constant.SERVER_PORT;

/**
 * Created by lhl on 2019/12/7.
 */
public class ClientUtil {

    private ClientThread clientThread;
    private Thread thread;
    private Handler handler;
    public String message;
    private ClientUtil() {
        handler = new Handler();
    }

    public static ClientUtil getInstance() {
        return ClientUtil.Holder.instance;
    }

    private static class Holder {
        private static final ClientUtil instance = new ClientUtil();
    }

    public void connectServer() {
        clientThread = new ClientThread();
        thread = new Thread(clientThread);
        thread.start();
    }

    public void sendClientMessage(String msg) {
        if (TextUtils.isEmpty(msg))
            return;
        showMessage(msg, Color.BLUE, false);
        if (null != clientThread) {
            if (msg.length() > 0) {
                clientThread.sendMessage(msg);
            }
        }
    }

    public void showMessage(final String message, final int color, final Boolean value) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                LogUtils.d("lhl", "ClientUtil   >>>" + message + "\n" + color + "\n" + value);
            }
        });
    }

    class ClientThread implements Runnable {

        private Socket socket;
        private BufferedReader input;

        @Override
        public void run() {

            try {

                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                showMessage("Connecting to Server...", 0, true);
                ToastUtils.showShort(MendoApplication.getApplication().getString(R.string.connecting_server));
                socket = new Socket(serverAddr, SERVER_PORT);

                if (socket.isBound()) {

                    showMessage("Connected to Server...", 0, true);
                    ToastUtils.showShort(MendoApplication.getApplication().getString(R.string.connect_server_success));
                    EventBusUtil.getInstance().postEvent(new Event(Constant.Events.CLIENT2SERVERSUCCESS,true));
                }


                while (!Thread.currentThread().isInterrupted()) {


                    this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    message = input.readLine();
                    if (null == message || "Disconnect".contentEquals(message)) {
                        Thread.interrupted();
                        message = "Server Disconnected...";
                        showMessage(message, Color.RED, false);
                        ToastUtils.showShort(message);
                        break;
                    }
                    showMessage("Server: " + message, 0, true);
                    if(message.contains("Fire"))
                    {
                        EventBusUtil.getInstance().postEvent(new Event(Constant.Events.POSTFIRECMD,message));
                    }
                    ToastUtils.showShort(message);
                }

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                showMessage("Problem Connecting to server... Check your server IP and Port and try again", Color.RED, false);
                ToastUtils.showShort(MendoApplication.getApplication().getString(R.string.check_whether_ip_exit));
                Thread.interrupted();
                e1.printStackTrace();
            } catch (NullPointerException e3) {
                showMessage("error returned", Color.RED, true);
                ToastUtils.showShort(MendoApplication.getApplication().getString(R.string.abnormal));
            }

        }

        void sendMessage(final String message) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (null != socket) {
                            PrintWriter out = new PrintWriter(new BufferedWriter(
                                    new OutputStreamWriter(socket.getOutputStream())),
                                    true);
                            out.println(message);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

    }

    private String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        return sdf.format(new Date());
    }

    public void disconnectClient() {
        if (null != clientThread) {
            clientThread.sendMessage("Disconnect");
            clientThread = null;
        }
    }

}
